import { writeFile } from 'fs/promises'
import { NextRequest, NextResponse } from 'next/server'
import path from 'path'

export async function POST(request: NextRequest) {
    console.log("开始处理文件上传请求")
    try {
        console.log("正在读取文件数据...")
        const file = request.body
        const contentType = request.headers.get("content-type") || "application/octet-stream"
        const fileName = request.headers.get("x-vercel-filename") || "image.png"

        if (!file) {
            console.log("错误：未检测到文件")
            return NextResponse.json({ success: false, message: "请选择文件" })
        }

        console.log(`接收到文件: ${fileName}, 类型: ${contentType}`)

        // 读取文件内容
        const arrayBuffer = await new Response(file).arrayBuffer()
        const buffer = Buffer.from(arrayBuffer)
        console.log(`buffer大小: ${buffer.length} bytes`)

        // 确保上传目录存在
        const uploadDir = path.join(process.cwd(),  'uploads')
        console.log(`上传目录: ${uploadDir}`)
        
        // 生成唯一文件名
        const uniqueFilename = `${Date.now()}-${fileName}`
        const filePath = path.join(uploadDir, uniqueFilename)
        console.log(`完整文件路径: ${filePath}`)
        
        // 写入文件
        console.log("开始写入文件...")
        await writeFile(filePath, buffer)
        console.log("文件写入成功")

        const fileUrl = `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/uploads/${uniqueFilename}`
        console.log(`文件访问URL: ${fileUrl}`)
        
        return NextResponse.json({
            success: true,
            url: fileUrl,
            fileInfo: {
                name: fileName,
                type: contentType,
                path: filePath
            }
        });
        
    } catch (error) {
        console.error("文件上传失败:", error)
        return NextResponse.json({ 
            success: false, 
            message: "上传失败",
            error: error instanceof Error ? error.message : "未知错误"
        })
    }
}